package main.com.cyz.LinkList;

import main.com.cyz.LinkList.Bean.ListNode;

/**
 * @author fox
 * @version 1.0
 * @description 力扣19
 * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 * <p>
 * 示例 1：
 * <p>
 * <p>
 * 输入：head = [1,2,3,4,5], n = 2
 * 输出：[1,2,3,5]
 * 示例 2：
 * <p>
 * 输入：head = [1], n = 1
 * 输出：[]
 * 示例 3：
 * <p>
 * 输入：head = [1,2], n = 1
 * 输出：[1]
 * <p>
 * <p>
 * 提示：
 * <p>
 * 链表中结点的数目为 sz
 * 1 <= sz <= 30
 * 0 <= Node.val <= 100
 * 1 <= n <= sz
 * @date 2024/5/17 18:55
 */
public class LeetCode19 {

    public static ListNode point(ListNode head, int target) {
        ListNode sentry = new ListNode(-1, head);
        ListNode beforeNode = sentry;
        ListNode end = sentry;
        for (int i = 1; i <= target + 1; i++) {
            end = end.next;
        }
        while (end != null) {
            end = end.next;
            beforeNode = beforeNode.next;
        }
        beforeNode.next = beforeNode.next.next;
        return sentry.next;
    }

    public static ListNode recursion(ListNode head, int target) {
        ListNode sentry = new ListNode(-1, head);
        r(sentry, target);
        return sentry.next;
    }

    private static int r(ListNode head, int target) {
        if (head.next == null) {
            return 0;
        }
        int num = r(head.next, target) + 1;
        if (num == target) {
            head.next = head.next.next;
        }
        return num;
    }

}
